//
//  Request.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/26/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//


//
//  Request.m
//  GIIPAccessDemo
//
//  Created by zhaolin on 14-3-17.
//  Copyright (c) 2014年 zhaolin. All rights reserved.
//

#import "Request.h"
#import "Response.h"
#import "JSONKit.h"
#import "AFNetworking.h"
#import "AFAppDotNetAPIClient.h"
#import "XDHeader.h"
#import "XDTools.h"

@implementation Request


-(void) addHeader:(NSMutableURLRequest*) request{
    id CFBundleVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    id CFBundleShortVersionString=[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSString* appVersion=[NSString stringWithFormat:@"%@(%@)",CFBundleShortVersionString,CFBundleVersion];
    id CFBundleIdentifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    //NSString* udid = [[NSUserDefaults standardUserDefaults] stringForKey:@"UDID"];
    NSString * udid;
    if (IS_NOT_EMPTY([XDTools readPassWord])){
        if (![[XDTools readPassWord] isEqualToString: [XDTools sharedXDTools].ud]){
            udid = [XDTools sharedXDTools].ud;
        }else{
            udid = [XDTools readPassWord];
        }
    }else{
        udid = [XDTools sharedXDTools].ud;
    }
    
    //一定不能少
    [request setValue:@"3.0" forHTTPHeaderField:@"giipVersion"];
    [request setValue:appVersion forHTTPHeaderField:@"appVersion"];
    [request setValue:CFBundleIdentifier forHTTPHeaderField:@"appName"];
    
    
    //设备唯一标示应该是初始化时用户输入的设备标示,将udid放置到http header中
    [request setValue:udid forHTTPHeaderField:@"UDID"];
}

-(void) request:(NSString *)interfaceName  keyValue:(NSDictionary *)data completionHandler:(void (^)(ResponseData *))handler
{
    
    NSString* url = [NSString stringWithFormat:@"%@?m=%@",SERVERPATH,interfaceName];
    
    //能连接到互联网时才开始请求
    if([XDTools NetworkReachable]){
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:data error:nil];
        [self addHeader:request];
        //开始请求
        NSURLSessionDataTask *dataTask = [[AFAppDotNetAPIClient sharedClient] dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            NSLog(@"response＝%@",response);
            if (error) {
                NSLog(@"请求异常：%@", error);
                if (handler) {
                    ResponseData* data = [[ResponseData alloc] initWithDictionary:[@"{\"errorMsg\":\"无法连接到服务器\"}" objectFromJSONString]];
                    handler(data);
                }
            } else {
                NSLog(@"responseObject＝%@",responseObject);
                if (handler) {
                    ResponseData* data = [[ResponseData alloc] initWithDictionary:responseObject];
                    handler(data);
                }
            }
        }];
        [dataTask resume];
    }else{
        NSLog(@"网络异常: WiFi＝%d,WWAN = %d",[[[AFAppDotNetAPIClient sharedClient] reachabilityManager] isReachableViaWiFi],[[[AFAppDotNetAPIClient sharedClient] reachabilityManager] isReachableViaWWAN]);
        if (handler) {
            ResponseData* data = [[ResponseData alloc] initWithDictionary:[@"{\"errorMsg\":\"未连接到网络\"}" objectFromJSONString]];
            handler(data);
        }
    }

}

-(void) uploadFile:(NSString *)interfaceName keyValue:(NSDictionary*) data file:(NSArray *) fileArray progressObserver:(NSObject *)observer completionHandler:(void (^)(ResponseData* data))completionHandler{
    
    NSString* url = [NSString stringWithFormat:@"%@?m=%@",SERVERPATH,interfaceName];
    if([XDTools NetworkReachable]){
        
        
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            //使用utf-8编码
            NSData* contentJson = [[data JSONString] dataUsingEncoding:NSUTF8StringEncoding];
            
            
            [formData appendPartWithFormData:contentJson name:@"content_json"];
            MyFile * file1 = [fileArray firstObject];
            MyFile * file2 = [fileArray lastObject];
            
            NSInputStream * inputStream1 = [NSInputStream inputStreamWithFileAtPath:file1.path];
            NSInputStream * inputStream2 = [NSInputStream inputStreamWithFileAtPath:file2.path];
            [formData appendPartWithInputStream:inputStream1 name:@"breviaryphotos" fileName:file1.name length:file1.length mimeType:@"application/octet-stream"];
            [formData appendPartWithInputStream:inputStream2 name:@"photos" fileName:file2.name length:file2.length mimeType:@"application/octet-stream"];
            
        } error:nil];
        
        [self addHeader:request];
        
        NSProgress* progress;
        
        NSURLSessionUploadTask *uploadTask = [[AFAppDotNetAPIClient sharedClient] uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"请求异常：%@", error);
                if (completionHandler) {
                    ResponseData* data = [[ResponseData alloc] initWithDictionary:[@"{\"errorMsg\":\"无法连接到服务器\"}" objectFromJSONString]];
                    completionHandler(data);
                }
            } else {
                NSLog(@"responseObject＝%@",responseObject);
                if (completionHandler) {
                    ResponseData* data = [[ResponseData alloc] initWithDictionary:responseObject];
                    completionHandler(data);
                }
            }
        }];
        [uploadTask resume];
        
//        if(observer){
//            [progress addObserver:observer forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
//        }
        
    }else{
        NSLog(@"网络异常: WiFi＝%d,WWAN = %d",[[[AFAppDotNetAPIClient sharedClient] reachabilityManager] isReachableViaWiFi],[[[AFAppDotNetAPIClient sharedClient] reachabilityManager] isReachableViaWWAN]);
        if (completionHandler) {
            ResponseData* data = [[ResponseData alloc] initWithDictionary:[@"{\"errorMsg\":\"未连接到网络\"}" objectFromJSONString]];
            completionHandler(data);
        }
    }
}

-(void) downloadFile:(NSString *)url fileSavePath:(NSString*) savePath progressObserver:(NSObject *)observer successHandler:(void (^)())successHandler failHandler:(void (^)(NSString* errormsg))failHandler{
    
    NSString* fullUrl = [SERVERPATH stringByAppendingString:url];
    
    if([XDTools NetworkReachable]){
        
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:fullUrl parameters:nil error:nil];
        
        [self addHeader:request];
        
        NSProgress* progress;
        NSURLSessionDownloadTask *downloadTask = [[AFAppDotNetAPIClient sharedClient] downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            return [[NSURL alloc] initFileURLWithPath:savePath];
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            [progress removeObserver:self forKeyPath:@"completedUnitCount" context:NULL];
            if (error) {
                NSLog(@"下载文件失败 response＝%@",response);
                if (failHandler) {
                    failHandler(@"文件下载失败");
                }
            }else{
                NSLog(@"下载文件成功 response＝%@",response);
                if (successHandler) {
                    successHandler();
                }
            }
        }];
        [downloadTask resume];
        if(observer){
            [progress addObserver:observer forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
        }
        
    }else{
        NSLog(@"网络异常: WiFi＝%d,WWAN = %d",[[[AFAppDotNetAPIClient sharedClient] reachabilityManager] isReachableViaWiFi],[[[AFAppDotNetAPIClient sharedClient] reachabilityManager] isReachableViaWWAN]);
        if (failHandler) {
            failHandler(@"未连接到网络");
        }
    }
}


@end
